package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")

public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 根据请求路径上传图片到服务器
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upLoad(MultipartFile file)  {


        log.info("图片文件为：{}",file.toString());

        //根据随机生成的号码 + 由原文件名称截取下来的文件格式名称
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.indexOf("."));
        String fileName = UUID.randomUUID() + suffix;

        //先判断此文件包是否存在 没有创建文件夹
        File dir = new File(basePath);

        if (!dir.exists())  dir.mkdirs();

        //将文件转存到该文件夹下面
        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return R.success(fileName);
    }

    @GetMapping("/download")

    public void download(String name , HttpServletResponse response)  {

        //创建输入输出流把文件下载到前端页面

        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));

            ServletOutputStream outputStream = response.getOutputStream();

            int len = 0;
            byte[] bytes = new byte[1024];

            while ((len=fileInputStream.read(bytes))!=-1){

                outputStream.write(bytes,0,len);

                outputStream.flush();

            }

            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
